<?php
namespace Home\Controller;

use Common\Service\Curl;
use Think\Controller;

class UserController extends Controller
{
    public function login()
    {
        $this->display();
    }

    public function logout()
    {
        session("user_id", null);
        $this->redirect('user/login');
    }

    /**
     * 用户登录
     */
    public function do_login()
    {
        $mobile = I('mobile', '', 'trim');
        $code   = I('code', '', 'trim');

        if (!preg_match("/^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0-9]))\\d{8}$/", $mobile)) {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '手机号错误']);
        }

        if ($code != session('rand_key')) {
            $this->ajaxReturn(['status' => false, 'code' => 1002, 'msg' => '验证码错误']);
        }

        if ($mobile != session('mobile')) {
            $this->ajaxReturn(['status' => false, 'code' => 1002, 'msg' => '非法操作']);
        }

        $res = M('user')->where(['mobile' => $mobile])->find();
        if ($res) {

            //参考"记住我",设置登录时效问题
            $salt = random_str(16);
            //第二分身标识
            $identifier = md5($salt . md5($mobile . $salt));
            //登录标识
            $token = md5(uniqid(rand(), true));
            //登录超时时间(60天)
            $timeout = time() + 3600 * 24 * 60;
            //存入cookie 注意后面的 / 没有的话，跳转页面就会失效
            setcookie('auth', "$identifier:$token", $timeout, '/');
            M('user')->where(['id' => $res['id']])->save([
                'identifier' => $identifier,
                'token'      => $token,
                'timeout'    => $timeout,
            ]);

            $data = [
                'id'          => $res['id'],
                'mobile'      => $res['mobile'],
                'nickName'    => $res['nickname'],
                'headUrl'     => $res['headimg'],
                'description' => $res['description'],
            ];

            $ret = ['status' => true, 'code' => 1000, 'msg' => '登陆成功', 'data' => $data];
            $this->ajaxReturn($ret);
        }
    }

    /**
     * 用户设置,修改密码
     */
    public function editPwd()
    {
        $userId = I('userId', '', 'trim');
        $oldPwd = I('oldPwd', '', 'trim');
        $newPwd = I('newPwd', '', 'trim');

        if (!$userId || !$newPwd) {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '请填写完整用户信息']);
        }

        $userInfo = M('user')->where(['id' => $userId])->find();
        if ($userInfo['password']) {
            if (!$oldPwd || $oldPwd != $userInfo['password']) {
                $this->ajaxReturn(['status' => false, 'code' => 1002, 'msg' => '请填写正确的原始密码！']);
            }
        }

        $rs = M('user')->where(['id' => $userId])->save(['password' => $newPwd]);
        if ($rs) {
            $this->ajaxReturn(['status' => true, 'code' => 1000, 'msg' => '设置密码成功！']);
        } else {
            $this->ajaxReturn(['status' => false, 'code' => 1003, 'msg' => '设置密码失败！']);
        }
    }

    /**
     * 设置用户个人信息页面展示
     * @return [type] [description]
     */
    public function showUpd()
    {
        $userId      = session('user_id');
        $model       = M('user');
        $where['id'] = $userId;
        $data        = $model->where($where)->find();
        $this->assign('data', $data);
        $this->assign('userId', $userId);
        $this->display('set');
    }

    /**
     * 用户信息更新
     */
    public function update()
    {
        $info = I('', '', 'trim');
        if (isset($info['nickName'])) {
            $data['nickname'] = $info['nickName'];
        }

        if (isset($info['mobile'])) {
            $data['mobile'] = $info['mobile'];
        }

        if (isset($info['email'])) {
            $data['email'] = $info['email'];
        }

        if (isset($info['headimg'])) {
            $data['headimg'] = $info['headimg'];
        }

        if (isset($info['description'])) {
            $data['description'] = $info['description'];
        }

        if (isset($info['remark'])) {
            $data['remark'] = $info['remark'];
        }

        $data['update_time'] = time();
        $rs                  = M('user')->where(['id' => $info['userId']])->find();
        if (!$rs) {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '用户id异常']);
        }

        $res = M('user')->where(['id' => $info['userId']])->save($data); //无数据更新的时候  返回值0
        if ($res == 0 || $res) {
            $this->ajaxReturn(['status' => true, 'code' => 1000, 'msg' => '更新成功']);
        } else {
            $this->ajaxReturn(['status' => false, 'code' => 1002, 'msg' => '数据库更新失败']);
        }
    }

    /**
     * 发送验证码
     */
    public function smscode()
    {
        $mobile = I('mobile', '', 'trim');
        if (!preg_match("/^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0-9]))\\d{8}$/", $mobile)) {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '手机号错误']);
        }

        $uinfo = M('user')->where(['mobile' => $mobile])->find();

        if (!$uinfo) {
            $this->ajaxReturn(['status' => false, 'code' => 1001, 'msg' => '该手机号非内部人员']);
        }

        $res = $this->sendcode($mobile);
        if ($res) {
            $arr = [
                'mobile'  => $mobile,
                'code'    => $res,
                'status'  => 1,
                'addtime' => time(),
            ];
            M('sms_code')->add($arr);

            $this->ajaxReturn(['status' => true, 'code' => 1000, 'msg' => '短信发送成功', 'data' => ['mobile' => $mobile, 'num' => $res]]);
        }

        $this->ajaxReturn(['status' => false, 'code' => 1004, 'msg' => '短信发送失败']);
    }

    public function sendcode($mobile)
    {
        $url      = 'http://39.108.85.254:8088/sms.aspx';
        $pool     = '0123456789';
        $rand_key = '';
        for ($i = 0; $i < 4; $i++) {
            $rand_key .= substr($pool, mt_rand(0, strlen($pool) - 1), 1);
        }
        $params = array(
            'action'   => 'send',
            'account'  => 'liang106',
            'userid'   => '201',
            'password' => 'liang106',
            'mobile'   => $mobile,
            'content'  => '【华南世茂】您的验证码：' . $rand_key,
            'action'   => 'send',
        );
        $res = Curl::request(POST, $url, $params);

        $xml     = simplexml_load_string($res);
        $xmljson = json_encode($xml);
        $arr     = json_decode($xmljson, true);

        if ($arr['returnstatus'] == 'Success') {
            session('mobile', $mobile);
            session('rand_key', $rand_key);
            return $rand_key;

        } else {
            return false;
        }
    }
}
